package com.goscom.app.deeset;

import com.goscom.app.database.DBAdapter;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class Rehabilitation extends Activity {

	private String strMerId = "";
	private DBAdapter mDB;
	private EditText edtDetail;
	private CheckBox ckbConvicted;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rehabilitation);

		edtDetail = (EditText) findViewById(R.id.edtRehaDetail);
		ckbConvicted = (CheckBox) findViewById(R.id.ckbRehaConvicted);

		mDB = new DBAdapter(Rehabilitation.this);
		mDB.open();

		getMerId();
	}

	public void getMerId() {
		try {
			strMerId = getIntent().getStringExtra("merid");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (strMerId != null) {
			ContentValues content = new ContentValues();
			content = mDB.queryDataByMerId("REHABILITATION", strMerId);
			if (content != null) {
				edtDetail.setText(content.getAsString("detail"));
				if (content.getAsString("convicted").equals("1")) {
					ckbConvicted.setChecked(true);
				}
			}
		}
	}

	public void Logout(View v) {
		saveDB();
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(Rehabilitation.this, Login.class));
	}

	public void goPrevious(View v) {
		saveDB();
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(Rehabilitation.this, ContactEmergency.class)
				.putExtra("merid", strMerId));
	}

	public void goNext(View v) {
		saveDB();
		if (mDB != null) {
			mDB.close();
		}
		startActivity(new Intent(Rehabilitation.this, Additional.class)
				.putExtra("merid", strMerId));
	}

	public void Save(View v) {
		saveDB();
		Toast.makeText(Rehabilitation.this, "Save Successful!",
				Toast.LENGTH_LONG).show();
	}

	public void saveDB() {
		if (mDB.queryMerchandiser("REHABILITATION", strMerId) == 0) {
			insertDB();
		} else {
			mDB.deleteData("REHABILITATION", strMerId);
			insertDB();
		}
	}

	public void insertDB() {
		ContentValues content = new ContentValues();
		content.put("merid", strMerId);
		content.put("convicted", ckbConvicted.isChecked());
		content.put("detail", edtDetail.getText().toString());
		mDB.insertData("REHABILITATION", content);
	}

	@Override
	protected void onRestart() {
		mDB.open();
		super.onRestart();
	}

	@Override
	protected void onDestroy() {
		if (mDB != null) {
			mDB.close();
		}
		super.onDestroy();
	}
}
